/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.elf.gwt.admin.client.subcomponents;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.elf.gwt.admin.client.AdminComponentController;
import com.elf.gwt.admin.client.components.CategoriesProductsComponent;
import com.elf.gwt.admin.client.components.CurrenciesAdministrationComponent;
import com.elf.gwt.admin.client.utils.AdminUtils;
import com.elf.gwt.common.client.callback.SubComponentCallback;
import com.elf.gwt.common.client.components.CommonSimpleComponent;
import com.elf.gwt.common.client.model.CategoryModel;
import com.elf.gwt.common.client.model.DetailedProductModel;
import com.elf.gwt.common.client.utils.CommonUtils;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.ListBox;

/**
 *  
 */
public class ProductSubComponent extends AdminSubComponent
{
	protected CategoriesProductsComponent component;
	protected DetailedProductModel productModel;
	protected Grid grid;

	protected HorizontalPanel buttonPanel = null;
	protected Button editButton;
	protected Button editXsellButton;
	protected Button copyButton;
	protected Button moveButton;
	protected Button newLinkButton;
	protected Button deleteButton;
	protected String newLink = "0";
	protected ListBox categoryListBox;

	protected String action = "";

	/**
	 * Constructor
	 */
	public ProductSubComponent(CommonSimpleComponent component, DetailedProductModel productModel, AdminComponentController controller, String handle, SubComponentCallback callback)
	{
		super(controller, handle, null, callback);
		this.productModel = productModel;
		this.component = (CategoriesProductsComponent)component;
	}

	public void build()
	{
		action = "";

		Image image = new Image();
		String imageUrl = AdminUtils.getImageProductsDirectory() + productModel.getImage();
		image.setUrl(imageUrl);
		image.setTitle(productModel.getName());
		String[] imageSize = productModel.getImageSize();
		image.setSize(imageSize[0], imageSize[1]);

		grid = new Grid(12, 1);

		DateTimeFormat df = CommonUtils.dateTimeFormat;
		Date dateAvailable = productModel.getDateAvailable();
		Date dateAdded = productModel.getDateAdded();
		Date lastModified = productModel.getDateModified();

		grid.setText(0, 0, productModel.getName());
		if (dateAvailable != null && dateAvailable.after(new Date())) grid.setText(2, 0, "Date Available: " + df.format(dateAvailable));
		if (dateAdded != null) grid.setText(3, 0, "Date Added: " + df.format(dateAdded));
		if (lastModified != null) grid.setText(4, 0, "Last Modified: " + df.format(lastModified));


		grid.setWidget(6, 0, image);
		grid.setText(7, 0, productModel.getImage());
		double price = productModel.getPrice();
		double specialPrice = productModel.getSpecialPrice();
		if (currenciesAdministrationComponent == null) currenciesAdministrationComponent = (CurrenciesAdministrationComponent)controller.getComponent("CurrenciesAdministrationComponent");
		grid.setHTML(9, 0, "Price: " + CommonUtils.priceDisplay(currenciesAdministrationComponent.getCurrencyModel(), price));
		if (price != specialPrice) grid.setHTML(10, 0, "Special Price: " + CommonUtils.priceDisplay(currenciesAdministrationComponent.getCurrencyModel(), specialPrice));
		grid.setText(11, 0, "Quantity: " + productModel.getInventoryQuantity());

		if (buttonPanel == null) 
		{
			buttonPanel = new HorizontalPanel();
			buttonPanel.setStyleName("ZButtons");

			editButton = new Button("edit", editHandler);
			editButton.addStyleName("ComponentLink");
			buttonPanel.add(editButton);
			buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

			editXsellButton = new Button("edit xsell", editXsellHandler);
			editXsellButton.addStyleName("ComponentLink");
			buttonPanel.add(editXsellButton);
			buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

			deleteButton = new Button("delete", deleteHandler);
			deleteButton.addStyleName("ComponentLink");
			buttonPanel.add(deleteButton);
			buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

			copyButton = new Button("copy", copyHandler);
			copyButton.addStyleName("ComponentLink");
			buttonPanel.add(copyButton);
			buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

			moveButton = new Button("move", moveHandler);
			moveButton.addStyleName("ComponentLink");
			buttonPanel.add(moveButton);
			buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

			newLinkButton = new Button("new link", newLinkHandler);
			newLinkButton.addStyleName("ComponentLink");
			buttonPanel.add(newLinkButton);
		}

		clear();
		add(new InlineHTML("<br/><br/><br/>"));
		add(buttonPanel);
		add(grid);

	}

	protected ClickHandler editHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			superAction = "EditProduct";
			callback.onNavigate(thisComponent);
		}
	};

	protected ClickHandler editXsellHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			superAction = "EditProductXsell";
			callback.onNavigate(thisComponent);
		}
	};

	protected ClickHandler moveHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			DialogBox dialogBox = createMoveDialogBox("0");
			dialogBox.center();
			dialogBox.show();
		}
	};

	protected ClickHandler deleteHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			if (Window.confirm("Delete Product?")) {
				superAction = "DeleteProduct";
				callback.onSuccess(thisComponent);
			}
		}
	};

	protected ClickHandler newLinkHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			DialogBox dialogBox = createMoveDialogBox("1");
			dialogBox.center();
			dialogBox.show();
		}
	};

	protected ClickHandler copyHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			DialogBox dialogBox = createMoveDialogBox("2");
			dialogBox.center();
			dialogBox.show();
		}
	};

	protected DialogBox createMoveDialogBox(String newLink1) {
		this.newLink = newLink1;
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setStyleName(component.getHandle()+ "DialogBox");
		dialogBox.addStyleName("DialogBox");
		dialogBox.setText("Select New Parent Category");
		FlowPanel dialogContents = new FlowPanel();
		dialogBox.setWidget(dialogContents);
		categoryListBox = new ListBox();
		categoryListBox.addChangeHandler(new ChangeHandler() {
			public void onChange(ChangeEvent event) {
				ListBox listBox = (ListBox)event.getSource();
				int index = listBox.getSelectedIndex();
				String value = listBox.getValue(index);
				if (value != null)
				{
					int id = Integer.parseInt(value);
					CategoryModel cmodel = component.getCategoryModel(id);
					if (cmodel.getChildList().size() == 0)
					{
						component.setSelectedCategoryId(id);
						if (newLink.equals("0"))
							superAction = "MoveProduct";
						else if (newLink.equals("1"))
							superAction = "NewProductLink";
						else if (newLink.equals("2"))
							superAction = "CopyProduct";
						dialogBox.hide();
						callback.onSuccess(thisComponent);
					}
				}
			}
		});

		dialogContents.add(categoryListBox);
		Button goButton = new Button("Go",
				new ClickHandler() {
			public void onClick(ClickEvent event) {
				int id = component.getSelectedCategoryId();
				CategoryModel cmodel = component.getCategoryModel(id);
				if (cmodel.getChildList().size() == 0)
				{
					component.setSelectedCategoryId(id);
					if (newLink.equals("0"))
						superAction = "MoveProduct";
					else if (newLink.equals("1"))
						superAction = "NewProductLink";
					else if (newLink.equals("2"))
						superAction = "CopyProduct";
					dialogBox.hide();
					callback.onSuccess(thisComponent);
				}
			}
		});
		dialogContents.add(goButton);
		Button closeButton = new Button("cancel",
				new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
			}
		});
		dialogContents.add(closeButton);

		categoryListBox.addItem("--Please Select--","-1");

		buildCategoryListBox(categoryListBox, component.getCategoryModel(0), component.getSelectedCategoryId(), "");
		return dialogBox;
	}

	public static void buildCategoryListBox(ListBox listBox, CategoryModel cmodel, int selectedCategoryId, String prefix)
	{		
		//if (cmodel.getChildList().size() == 0) {
		listBox.addItem(prefix + cmodel.getName(),String.valueOf(cmodel.getId()));
		if (cmodel.getId() == selectedCategoryId) listBox.setSelectedIndex(listBox.getItemCount() - 1);
		//}
		List<CategoryModel> children = cmodel.getChildList();
		Iterator<CategoryModel> iter = children.iterator();
		while(iter.hasNext())
		{
			CategoryModel child = iter.next();
			buildCategoryListBox(listBox, child, selectedCategoryId, prefix + "+");
		}
	}
}
